<template>
  <div class="attachment-viewer">
    <!-- 文件列表 -->
    <span v-if="!fileList.length">暂无附件</span>
    <el-card
        v-else
        body-style="padding: 10px"
        class="file-list"
        shadow="never"
    >
      <template #header>
        <div class="header">
          <span class="file-count">共 {{ fileList.length }} 个文件</span>
        </div>
      </template>

      <el-scrollbar max-height="400px">
        <div v-for="(file, index) in fileList" :key="index" class="file-item">
          <div class="file-info">
            <!-- 文件图标 -->
            <el-icon class="file-icon">
              <Document/>
            </el-icon>
            <!-- 文件名称 -->
            <span class="file-name">{{ file.name }}</span>
          </div>
          <div>
            <el-button icon="view" link @click="handlePreview(file)">预览</el-button>
            <el-button icon="Download" link type="primary" @click="handleDownload(file)">
              下载
            </el-button>
          </div>
        </div>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<script setup>
import {Document} from '@element-plus/icons-vue'
import {ElLoading, ElMessage} from 'element-plus'
import request from "@/utils/request.js"

// 通过 defineModel 实现 v-model:fileList 双向绑定
const fileList = defineModel('fileList', {default: () => []})

const handlePreview = (file) => {
  window.open(file.url, '_blank')
}

const handleDownload = async (file) => {
  const loading = ElLoading.service()
  try {
    await request.post(`/file/download/${encodeURIComponent(file.filename)}`, {}, {
      responseType: 'blob'
    })
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败，请重试')
  } finally {
    loading.close()
  }
}
</script>

<style scoped>
.attachment-viewer {
  width: 100%;
}

.file-list {
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-count {
  color: #909399;
  font-size: 14px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
}

.file-item:last-child {
  border-bottom: none;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  font-size: 20px;
  color: #909399;
}

.file-name {
  color: #606266;
}
</style>